import { ComSeriveProvider } from './../../../providers/com-serive/com-serive';
import { Component } from '@angular/core';
import {
  IonicPage,
  NavController,
  NavParams,
  ToastController,
  ActionSheetController,
  AlertController,
  App
} from 'ionic-angular';
import { BaseUI } from '../../../common/baseUI';
import { FileTransfer, FileTransferObject } from '@ionic-native/file-transfer';
import { Camera } from '@ionic-native/camera';
import { LoadingController, Platform } from 'ionic-angular';

@IonicPage()
@Component({
  selector: 'page-updata-info',
  templateUrl: 'updata-info.html'
})
export class UpdataInfoPage extends BaseUI {
  nickname: string = ''; // 昵称
  realname: string = ''; // 真名
  classes: string = ''; // 班级
  qq: string = ''; // QQ号码
  cucumber: boolean; // checkbox是否选中
  default;
  qqs = '';

  gradename = [];
  majorname = [];
  classesname = [];
  newClass = [];

  //拍照上传之后图片返回的地址
  photoReturnUrl =
    'http://netx-check.oss-cn-shenzhen.aliyuncs.com/photo/1533191152234.png';
  pictures: any = [];
  //预览图片的地址
  picturesFullPath: any = [];
  picturesTemp;
  isMe = true;
  userId;

  isShowPhoneBorder: boolean = false;
  isShowCodeBorder: boolean = false;
  isShowPasswordBorder: boolean = false;
  isShowRepasswordBorder: boolean = false;
  isShowNicknameBorder: boolean = false;
  isShowRealnameBorder: boolean = false;
  isShowClassesBorder: boolean = false;
  isShowQQBorder: boolean = false;

  // ionic native File Transfer
  fileTransfer: FileTransferObject = this.transfer.create();

  // 接收电话 密码
  phone: string;
  password: string;
  dependentColumns = [];

  // 限制弹窗
  count = 0;

  constructor(
    public navCtrl: NavController,
    public navParams: NavParams,
    public toastCtrl: ToastController,
    public camera: Camera,
    public transfer: FileTransfer,
    public actionSheetCtrl: ActionSheetController,
    public loadingCtrl: LoadingController,
    public comSerive: ComSeriveProvider,
    public alertCtrl: AlertController,
    public app: App,
    public platform: Platform
  ) {
    super();
    this.phone = this.navParams.get('phone');
    this.password = this.navParams.get('password');
  }

  ionViewDidLoad() {
    this.getClassesData();
  }

  // 完成注册
  complete() {
    // 去除空格 取班级 例如（16 16软件 1 => 16软件1）
    this.classes =
      this.classes.substring(3, this.classes.lastIndexOf(' ')) +
      this.classes.substr(this.classes.lastIndexOf(' ') + 1);

    const stringuser = JSON.stringify({
      phone: this.phone,
      password: this.password,
      avatar: this.photoReturnUrl,
      nickname: this.nickname,
      realname: this.realname,
      userqq: this.qq,
      classes: this.classes
    });

    const pattern = /^[\u4E00-\u9FA5\uf900-\ufa2d·s]{2,20}$/;
    if (
      this.photoReturnUrl === null ||
      this.photoReturnUrl === undefined ||
      this.photoReturnUrl === ''
    ) {
      this.isShowToast('头像不能为空');
    } else if (this.nickname.trim().length < 1) {
      // this.showToast(this.toastCtrl, '昵称不能为空');
      this.isShowToast('昵称不能为空');
    } else if (!pattern.test(this.realname)) {
      this.isShowToast('请输入正确的姓名');
    } else if (this.classes.length === 0) {
      this.isShowToast('班级不能为空');
    } else if (this.qq.trim().length === 0) {
      this.isShowToast('QQ号码不能为空');
    } else if (this.qq.trim().length < 6 || this.qq.trim().length > 10) {
      this.isShowToast('请输入正确的QQ号码');
    } else if (this.classes.length < 5) {
      this.isShowToast('请输入正确的班级');
    } else {
      this.comSerive.userRegister(stringuser).subscribe(data => {
        if (data['status'] === 200) {
          this.isShowToast('注册成功，前往登录页面');
          this.presentAlert();
        } else if (data['staus'] === 400) {
          this.isShowToast('该账户已经注册');
        } else {
          this.isShowToast('服务繁忙，请稍后再试');
        }
      });
    }
  }

  isEmoji($event) {
    this.nickname = this.nickname.replace(
      /[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF][\u200D|\uFE0F]|[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF]|[0-9|*|#]\uFE0F\u20E3|[0-9|#]\u20E3|[\u203C-\u3299]\uFE0F\u200D|[\u203C-\u3299]\uFE0F|[\u2122-\u2B55]|\u303D|[\A9|\AE]\u3030|\uA9|\uAE|\u3030/gi,
      ''
    );
  }

  // / 放大图片
  zoomImage(index) {
    this.navCtrl.push('SlidePhotoPage', {
      i: index,
      photo: this.picturesFullPath
    });
  }

  //头像上传成功之后触发
  pickPictures($event) {
    //$event[0] 图片上传之后服务器返回的数据
    this.pictures = $event.pictures;
    this.photoReturnUrl = this.pictures[0].data;
  }

  //删除图片触发
  deletedPictures($event) {
    this.photoReturnUrl = null;
  }

  // 限制重复弹窗
  isShowToast(message) {
    if (this.count === 0) {
      this.showToast(this.toastCtrl, message);
      this.count++;
      setTimeout(() => {
        this.count = 0;
      }, 3000);
    }
  }

  // 返回上一级
  pop() {
    this.navCtrl.pop();
  }

  getClassesData() {
    this.comSerive.getClass().subscribe(data => {
      for (var key in data) {
        // console.log(data[key]);
        let obj1 = { text: key, value: key };
        this.gradename.push(obj1);
        for (var k in data[key]) {
          let obj2 = { text: k, value: key + k, parentVal: key };
          this.majorname.push(obj2);
          for (const j in data[key][k]) {
            // console.log(data[key][k][j]['classesname']);
            let txt = data[key][k][j]['classesname'];
            let obj3 = { text: txt + '', value: txt, parentVal: key + k };

            this.classesname.push(obj3);
            // console.log(this.classesname);
          }
        }
      }
    });

    this.dependentColumns = [
      {
        options: this.gradename
      },
      {
        options: this.majorname
      },
      {
        options: this.classesname
      }
    ];
  }

  // alert 提示跳去登录界面
  presentAlert() {
    let alert = this.alertCtrl.create({
      title: '去登录',
      buttons: [
        {
          text: '确定',
          handler: () => {
            this.app.getRootNav().setRoot('LoginPage');
          }
        }
      ]
    });
    alert.present();
  }

  // 限制输入e
  passwordReplace($event) {
    if ($event.keyCode == 8 && this.qq.length == 0) {
      this.qq = this.qqs = '';
      return;
    }
    //通过phone保存值的改变 来判断用户是否输入非法字符
    //输入非法字符后input的值会突然为空
    if (this.qq != '') {
      this.qqs = this.qq;
    } else {
      this.qq = this.qqs == '' ? '中文触发number' : this.qqs;
    }
    this.qq = this.qq.replace(/[eE\.]/, '');
  }

  // 聚焦手机号
  focusShowPhoneBorder() {
    this.isShowPhoneBorder = true;
  }
  // 失焦验证码
  blurShowCodeBorder() {
    this.isShowCodeBorder = false;
  }
  // 聚焦验证码
  focusShowCodeBorder() {
    this.isShowCodeBorder = true;
  }
  // 失焦密码
  blurShowPasswordBorder() {
    this.isShowPasswordBorder = false;
  }
  // 聚焦密码
  focusShowPasswordBorder() {
    this.isShowPasswordBorder = true;
  }
  // 失焦重复验证密码
  blurShowRepasswordBorder() {
    this.isShowRepasswordBorder = false;
  }
  // 聚焦重复验证密码
  focusShowRepasswordBorder() {
    this.isShowRepasswordBorder = true;
  }
  // 失焦昵称
  blurShowNicknameBorder() {
    this.isShowNicknameBorder = false;
  }
  // 聚焦昵称
  focusShowNicknameBorder() {
    this.isShowNicknameBorder = true;
  }
  // 失焦真名
  blurShowRealnameBorder() {
    this.isShowRealnameBorder = false;
  }
  // 聚焦真名
  focusShowRealnameBorder() {
    this.isShowRealnameBorder = true;
  }
  // 失焦班级
  blurShowClassesBorder() {
    this.isShowClassesBorder = false;
  }
  // 聚焦班级
  focusShowClassesBorder() {
    this.isShowClassesBorder = true;
  }
  // 失焦QQ号
  blurShowQQBorder() {
    this.isShowQQBorder = false;
  }
  // 聚焦QQ号
  focusShowQQBorder() {
    this.isShowQQBorder = true;
  }
}
